/**
 * Property of Matteo Muscella, Abrar Rashwan and Talal El Achfal.
 * Code for the Grizzlies Tank group.
 * Red: 9f1b24
 */
    
// Listener for the complete loading of the page
window.addEventListener("load", app, false);
    
    function app() {
        
        // Start of the canvas
        canvas = jc.canvas("myCanvas01").start(true);
        
        /**
         * IMAGES
         * I've implemented this array because it's easy to load the different
         * image from it.
         * Each image is stored in a list, containing:
         * - path - X-position - Y-position - element-unique-id.
         * Each list makes up an Array.
         */
        var arrayOfImages = new Array();
        
        // image path - x-position - y-position - id
        
        // Init screen - Menu
        arrayOfImages[0] = ["img/bgs/bg.png", 0, 0, "menu_bg"];
        arrayOfImages[1] = ["img/menu/menu_side.png", 0, 10, "menu_sidebar"];
        arrayOfImages[2] = ["img/tanks/tank.png", 370, 378, "tank"];
        arrayOfImages[3] = ["img/logo/logo_big.png", 250, 100, "logo"];
            // Labels
        arrayOfImages[4] = ["img/labels/label_play_big.png", 35, 80, "label_play"];
        arrayOfImages[5] = ["img/labels/label_options.png", 35, 140, "label_options"];
        arrayOfImages[6] = ["img/labels/label_how2.png", 35, 200, "label_how2"];
        arrayOfImages[7] = ["img/labels/label_credit.png", 35, 260, "label_credit"];
        arrayOfImages[8] = ["img/buttons/audio_off.png", 50, 350, "audio_label"];
        
        // First level
        arrayOfImages[9] = ["img/bgs/bg_day.png", 0, 0, "bg_day"];
        arrayOfImages[10] = ["img/bgs/bg_bar.png", 0, 10, "bg_bar"];
            // Labels
        arrayOfImages[11] = ["img/labels/label_player1.png", 60, 20, "label_player1"];
        arrayOfImages[12] = ["img/labels/label_player2.png", 455, 20, "label_player2"];
        arrayOfImages[13] = ["img/labels/label_level.png", 225, 20, "label_level"];
            // Tanks
        arrayOfImages[14] = ["img/tanks/tankSx.png", 200, 380, "tankSx"];
        arrayOfImages[15] = ["img/tanks/tankDx.png", 360, 380, "tankDx"];
        
        // Second Level - same images.
        
        // Third Level
        // In the third level, the bg changes.
        arrayOfImages[16] = ["img/bgs/bg_night.png", 0, 0, "bg_night"];
        
        // Game Over
        arrayOfImages[17] = ["img/bgs/bg_gOver_box.png", 0, 0, "bg_gOver_box"];
        arrayOfImages[18] = ["img/labels/label_gOver_big.png", 140, 50, "label_gOver_big"];
        arrayOfImages[19] = ["img/tanks/tank_big.png", 130, 170, "tank_big"];
        
        // Options
        arrayOfImages[20] = ["img/labels/label_options_big.png", 180, 40, "label_options_big"];
        arrayOfImages[21] = ["img/labels/options_menu_text2.png", 40, 55, "options_labels_menu"];
        
        // How2
        arrayOfImages[22] = ["img/labels/label_how2_big.png", 200, 40, "how2_big"];
        arrayOfImages[23] = ["img/labels/labels_how2_text.png", 90, 120, "how2_labels_menu"];
        
        // Credit
        arrayOfImages[24] = ["img/labels/label_credit_big.png", 200, 40, "label_credit_big"];
        arrayOfImages[25] = ["img/labels/labels_text_credits.png", 90, 150, "credit_label"];
        
        // Other images
        arrayOfImages[26] = ["img/bgs/bg_stars.png", 0, 0, "bg_stars"];
        arrayOfImages[27] = ["img/bgs/bg_moon.png", 130, 60, "bg_moon"];
        arrayOfImages[28] = ["img/buttons/button_audio.png", 50, 350, "label_audio"];
        arrayOfImages[29] = ["img/buttons/arrow.png", 45, 430, "arrow"];
        arrayOfImages[30] = ["img/labels/label_play_big_hover.png", 35, 80, "label_play_hover"];
        
        
        // - End of the Array definition --------------------------------------
        
        
        // - VARIABLES --------------------------------------------------------
        
        /* GAME VARIABLES */
        
        var points = new Array(); // array of X,Y coordinates
        
        /* MIDPOINT PARAMETERS */
        
		var noS = 639; //set the number of final segments
		var mD = 180; //the maximum displacement of Y coordinate
		var minY = 240; //minimum value of Y coordinate
		var maxY = 400; //maximum value of Y coordinate
		var reduction = 0.4; //the amount to which mD is reduced at each iteration (it should be between 0 and 1)
        
       	points[1] = [0, Math.random() * (maxY - minY) + minY]; //any random number between minY and maxY
        points[noS+1] = [noS+1, Math.random() * (maxY - minY) + minY]; //any random number between minY and maxY
        
        
        /* VARIABLES FOR LOCAL STORAGE IN THE BROWSER */
        // for info --> http://diveintohtml5.info/storage.html
        
        /* GAMING SAVE */
        // this variable allows to not go back to the main menu unless requested.
        var gameInProgress = false;
        var audio = false;
        
        // these array contains the data of each player.
        var players = new Array();
        
        var player1Name = "Player 1";
        var player2Name = "Player 2";
        var player1TankColor = "#FF0000";
        var player2TankColor = "#0000FF";
        var player1Life = 4;
        var player2Life = 4;
        var player1ShootingAngle = 60;
        var player2ShootingAngle = 60;
        var player1turn = true;
        var player2turn = false;
        var val1 = -10;
        var val2 = 10;
        var windSpeed = Math.floor(val2 + (1+val1-val2)*Math.random());
        
                // Name - tank's color - lives remaining - shootingAngle
        players["player1"] = [player1Name, player1TankColor, player1Life, player1ShootingAngle];
        players["player2"] = [player2Name, player2TankColor, player2Life, player2ShootingAngle];        
        
        var keys1 = ["player1Name", "player1TankColor", "player1Life", "player1ShootingAngle"];
        var keys2 = ["player2Name", "player2TankColor", "player2Life", "player2ShootingAngle"];
        
        /* GAME SETTINGS VARIABLES */
        var chosenLevel = 1;

        // variables for the position of the shot
        var xp;
        var yp;
        
        // - WEAPONS VARIABLE
        var bulletVisibility = false;
        
        
        // --------------------------------------------------- MAIN FUNCTIONS -
        
        /**
         * Main function for drawing images
         * 
         * @param {String} source Path to the file
         * @param x {int} The X-position
         * @param y {int} The Y-position
         * @param elemId The id of the element.
         * @param visibiltyParam The boolean variable for the visibility of _
         * _ the object
         */
        function onload_images(source, x, y, elemId, visibilityParam) {
            var img=new Image();
            img.src=source;
            jc.image(img, x, y).id(elemId).visible(visibilityParam);
            
        };
        
        
        /**
         * Clears the canvas.
         */
        function clearsTheCanvas() {
            jc.canvas().clear();
        };
        
        
        /**
         * Go back to the main menu
         */
        function go2MainMenu() {
            console.log();
            //localStorage.clear();
            localStorage.removeItem("the.game.is.loaded");
            localStorage.removeItem("audio");
            canvas = jc.canvas("myCanvas01").start(true);
            init();
        };
        
        
        /**
         * Go to the options menu
         */
        function go2OptionsMenu() {
            console.log();
            optionsCanvas();
        };
        
        
        
        /**
         * Go to the how2 menu
         */
        function go2How2Menu() {
            console.log();
            how2Canvas();
        };
        
        
        /**
         * Go to the credit menu
         */
        function go2CreditMenu() {
            console.log();
            creditCanvas();
        };
        
        
        // - Functions to draw different elements/pages -----------------------
        
        /**
         * This function draws the background
         */
        function drawBg() {
            
            // Set this to 'false and make the elements invisible
            visibility = true;
            
            // Call 'onload images with the background
                // path - X-postion - Y-position - Id - Visibility(boolean)
            onload_images(
                          arrayOfImages[17][0],
                          arrayOfImages[17][1],
                          arrayOfImages[17][2],
                          arrayOfImages[17][3],
                          visibility
                          );        
        };
        
        
        /**
         * This function draws the arrow
         */
        function drawArrow() {
            
            // Set this to 'false and make the elements invisible
            visibility = true;
            
            // Call 'onload images with the arrow
            // path - X-postion - Y-position - Id - Visibility(boolean)
            onload_images(
                      arrayOfImages[29][0],
                      arrayOfImages[29][1],
                      arrayOfImages[29][2],
                      arrayOfImages[29][3],
                      visibility
                      );
                };
        
        
        /**
         * This function draws the How-to page.
         */
        function how2Canvas() {
            
            // Set this to 'false and make the elements invisible
            visibility = true;
            
            // draws background
            drawBg();
            
            // Iterate over the array of images and draw the images
            // calling 'onload_images
            for (var i = 22; i < 24; i++) {
                // Calling of 'onload_images with arguments
                // path - X-postion - Y-position - Id - Visibility(boolean)
                onload_images(
                              arrayOfImages[i][0],
                              arrayOfImages[i][1],
                              arrayOfImages[i][2],
                              arrayOfImages[i][3],
                              visibility
                              );  
            };
            
            // Arrow --> to go back
            drawArrow();
            
            // Event handler for the arrow
            jc('#arrow').click(go2MainMenu);
            jc('#arrow')
            .mouseover(function() {
            	console.log((jc('#arrow').opacity(0.6)));
            })
            .mouseout(function() {
            	console.log((jc('#arrow').opacity(1)));
            })
            ;
            
        };
        
        
        /**
         * This function draws the Options page.
         */
        function optionsCanvas() {
            
            // Set this to 'false and make the elements invisible
            visibility = true;
            
            // draw bg
            drawBg();
            
            // Options panel
            for (var j=20; j<22; j++) {
                 //Call 'onload images with the option stuff
                 //    path - X-postion - Y-position - Id - Visibility(boolean)
                onload_images(
                              arrayOfImages[j][0],
                              arrayOfImages[j][1],
                              arrayOfImages[j][2],
                              arrayOfImages[j][3],
                              visibility
                              );
            };
            
            
            /**
             * Draw the rectangle for the color picker
             */
            function drawRectangleColorPicker() {
                jc.rect(455, 330, 26, 26, "#0000ff", true).id("cPicker");
                onload_images("img/labels/selector.png", 450, 325, true);
            }
            
            
            //// Tanks for the options panel            
            //for (var j=14; j<16; j++) {
            //    // Call 'onload images with the tank
            //        // path - X-postion - Y-position - Id - Visibility(boolean)
            //    onload_images(
            //                  arrayOfImages[j][0],
            //                  arrayOfImages[j][1],
            //                  arrayOfImages[j][2],
            //                  arrayOfImages[j][3],
            //                  visibility
            //                  );
            //};
            
            
            onload_images("img/screenshots/inGame-l1.png", 330, 200, "level1", true);
            
            jc("#level1").scale(1/8);
            
            onload_images("img/screenshots/inGame-l2.png", 430, 200, "level2", true);
            
            jc("#level2").scale(1/8);
            
            jc("#level1").click(function() {
                chosenLevel=1;
                localStorage["the.chosen.level"] = chosenLevel;
                //alert(localStorage[settings["level"]])
            });
            
            jc("#level2").click(function() {
                chosenLevel = 2;
                localStorage["the.chosen.level"] = chosenLevel;
                //alert(localStorage[settings["level"]])
            });
            
            // Arrow
            drawArrow();
            
            // - Events
            // Event handler for the arrow
            jc('#arrow').click(go2MainMenu);
            jc('#arrow')
            .mouseover(function() {
            	console.log((jc('#arrow').opacity(0.4)));
            })
            .mouseout(function() {
            	console.log((jc('#arrow').opacity(1)));
            })
            ;
            
            jc('#level1')
            .mouseover(function() {
            	console.log((jc('#level1').opacity(0.2)));
            })
            .mouseout(function() {
            	console.log((jc('#level1').opacity(1)));
            })
            ;
            
            jc('#level2')
            .mouseover(function() {
            	console.log((jc('#level2').opacity(0.2)));
            })
            .mouseout(function() {
            	console.log((jc('#level2').opacity(1)));
            })
            ;
        };
        
        
        /**
         * This function draws the Credit page.
         */
        function creditCanvas() {
            
            // Set this to 'false and make the elements invisible
            visibility = true;
            
            // draw the bg
            drawBg();
            
            for (var j=24; j<26; j++) {
                // Call 'onload images with the credit stuff
                    // path - X-postion - Y-position - Id - Visibility(boolean)
                onload_images(
                              arrayOfImages[j][0],
                              arrayOfImages[j][1],
                              arrayOfImages[j][2],
                              arrayOfImages[j][3],
                              visibility
                              );
                };
            
            // Draw the arrow
            drawArrow();
            
            // - Events
            // Event handler for the arrow
            jc('#arrow').click(go2MainMenu);
            jc('#arrow')
            .mouseover(function() {
            	console.log((jc('#arrow').opacity(0.2)));
            })
            .mouseout(function() {
            	console.log((jc('#arrow').opacity(1)));
            })
            ;
        };
        
        
        // draws text with specified
        // string - x-position - y-position - id
        function drawText(String, x, y, id) {
            jc.text(String, x, y)
            //.font("15px Tahoma")
            .font("10px Destroy")
            //.font("20px Jolly Lodger")
            .color("#9f1b24")
            .id(id);
        }
        
        function drawTextForMain(String, x, y, id) {
            jc.text(String, x, y)
            //.font("22px Destroy")
            .font("36px Jolly Lodger")
            //.font("36px Arial")
            .color("#9f1b24")
            .id(id);
        }
        
        // draws player1shooting angle
        function drawAngleMod() {
            drawText(string, 200, 38, arrayOfImages[11][3]);
        }
        
        
        // draws label customized with names
        function drawInGameLabels() {
            console.log();
            h=38;
            // level label
            drawText("Level: "+localStorage["the.chosen.level"], 
            		285, 
            		h, 
            		arrayOfImages[13][3]);
            drawText("Wind Speed: "+windSpeed, 
            		490, 
            		68, 
            		arrayOfImages[13][3]);
        }
        
        function drawPlayer1label(x) {
        	h=38;
            // player 1 label
            drawText("P1 Life: "+player1Life+",  "+"Angle: "+x,
                     50,
                     h,
                     arrayOfImages[11][3]);
        }
        
        function drawPlayer2label(x) {
        	h=38;
        	// player 2 label
            drawText("P2 Life: "+player2Life+",  "+"Angle: "+x, 
            		450, 
            		h, 
            		arrayOfImages[12][3]);
        }
        
        
        // Draws the background for the first level
        function drawBgLevelOne()  {
            // Set this to 'false and make the elements invisible
            visibility = true;
            
            // Call 'onload images with the background
                // path - X-postion - Y-position - Id - Visibility(boolean)
            onload_images(
                          arrayOfImages[9][0],
                          arrayOfImages[9][1],
                          arrayOfImages[9][2],
                          arrayOfImages[9][3],
                          visibility
                          );        
        }
        
        
        function drawBgLevelTwo(){
            // Set this to 'false and make the elements invisible
            visibility = true;
            
            // Call 'onload images with the background
                // path - X-postion - Y-position - Id - Visibility(boolean)
            // Night bg
            onload_images(
                          arrayOfImages[16][0],
                          arrayOfImages[16][1],
                          arrayOfImages[16][2],
                          arrayOfImages[16][3],
                          visibility
                          );
            // Stars
            onload_images(
                          arrayOfImages[26][0],
                          arrayOfImages[26][1],
                          arrayOfImages[26][2],
                          arrayOfImages[26][3],
                          visibility
                          );
            // Moon
            onload_images(
                          arrayOfImages[27][0],
                          arrayOfImages[27][1],
                          arrayOfImages[27][2],
                          arrayOfImages[27][3],
                          visibility
                          );        
        }
        
        // draws different backgrounds
        function drawDiffBg() {
            if ( localStorage["the.chosen.level"] == "1" ) {
                drawBgLevelOne();
                return;
            } else {
                drawBgLevelTwo();
            }
        }
        
        
        // Draw the status bar
        function drawStatusBar() {
            // Set this to 'false and make the elements invisible
            visibility = true;
            
            // Call 'onload images with the status bar
                // path - X-postion - Y-position - Id - Visibility(boolean)
            onload_images(
                              arrayOfImages[10][0],
                              arrayOfImages[10][1],
                              arrayOfImages[10][2],
                              arrayOfImages[10][3],
                              visibility
                              );
        }
        
        
        
        
        // - MAIN GAME FUNCTIONS ----------------------------------------------
        
        /**
         * This function provides functionalities for the game
         */
        function playTheGame() {
//        	setInterval( function() {
            // Set this to 'false and make all the elements invisible
            // visibility = true;
            console.log();
            // set gameInProgress to true so as to call only game function
            changeGameState();
            // call to clears the canvas function to clear the canvas
            clearsTheCanvas();
            // Restart the canvas
            canvas = jc.canvas("myCanvas01").start(true);
            // background
            drawDiffBg();
            // call to midpoint displacement function
            midpoint(1, noS+1, mD, reduction);
            // call to draw terrain function
            drawTerrain();
            // bar for the game status
            drawStatusBar();
            // draws label customized with names
            drawInGameLabels();
            drawPlayer1label();
            drawPlayer2label();
            drawArrow();
            jc('#arrow')
            .mouseover(function() {
            	console.log((jc('#arrow').opacity(0.6)));
            })
            .mouseout(function() {
            	console.log((jc('#arrow').opacity(1)));
            });
            // Event handler for the arrow
            jc('#arrow').click(go2MainMenu);
            //alert(localStorage[settings["level"]])
            // bullets support
            bullets();
//            }, 1000/30);
        	
        };        
        
        
        /**
         * MidPoint Displacement Algorithm Function
         * (Terrain)
         */
	    function midpoint(start, end, mD, reduction) {
	        var middle = Math.round((start + end) / 2);
            if ((end - start <= 1) || middle == start || middle == end) {
		        return;
	        };
					
	        /* the do-while loop avoids to have Y values out of the 40-340 range */
	        do {
            
                var nY = (points[end][1] + points[start][1]) / 2 + mD * (1 - 2 * Math.random());
        
            } while (nY<minY || nY>maxY)
        
            points[middle] = [middle, nY];
            midpoint(start, middle, mD * reduction, reduction);
            midpoint(middle, end, mD * reduction, reduction);
	    };
        
        
	    /* CANVAS */
            // This function draws the terrain
			
	    function drawTerrain() {
                x = 0;
	        y = 480;
	        
                points[0]=[0,480];
                points[noS+2]=[640,480];
	    
                jc.line(points,'#A0522D',1);
            };
        
        
        // - Weapons ----------------------------------------------------------
        
        // first tank
            var tank1 = {
                x:80, //start pos x
                y:0, //start pos y
                r:16 //radius
            };
        
        // Other tank
            var tank2 = {
                x:545, //start pos x
                y:0, //start pos y
                r:16 //radius
            };
        
	
	
        function bullets() {
        
            var pro = {
                x:67, //start pos x
                y:0, //start pos y
                r:4, //radius
                v:70, //init velocity
                a: players["player1"][3] //angle
            };
	
	    var pro2 = {
                    x:566, //start pos x
                    y:0, //start pos y
                    r:4, //radius
                    v:70, //init velocity
                    a: players["player1"][3] //angle
            };
            
            pro.y = (points[pro.x][1]-pro.r);
    
            jc.circle(pro.x,pro.y,pro.r,'#ff0000', true)
            .visible(bulletVisibility)
            .id('p');
            
            jc('#p').click(
                    function(){
                            fire('#p', pro, 1);
                    }
            );
            
            
            
            pro2.y = (points[pro2.x][1]-pro2.r);
            
            jc.circle(pro2.x,pro2.y,pro2.r,'#0000ff', true)
            .visible(bulletVisibility)
            .id('p2');
            
            //jc('#p2').click(
              //      function(){
                       //     fire('#p2', pro2, -1);
                //    }
            //);
            
            // first tank
            var tank1 = {
                x:80, //start pos x
                y:0, //start pos y
                r:16 //radius
            };
            
            tank1.y = (points[tank1.x][1]-tank1.r);
            
            onload_images(
                arrayOfImages[14][0],
                tank1.x,
                tank1.y,
                arrayOfImages[14][3],
                visibility
                );
            //alert(tank1.y);
            
            
            // Other tank
            var tank2 = {
                x:545, //start pos x
                y:0, //start pos y
                r:16 //radius
            };
            
            tank2.y = (points[tank2.x][1]-tank2.r);
            
            onload_images(
                arrayOfImages[15][0],
                tank2.x,
                tank2.y,
                arrayOfImages[15][3],
                visibility
                );
            //alert(tank1.y);
            
            //alert(players["player1"][2])
	 
            
        /**
         * This function abilita the player1 to shoot.
         */
	    if (player1turn==true) {
		jc("#tankSx").click(function() {
		    //window.alert("Yeah it's working");
		    jc("#p2").visible(false);
		    jc("#p").visible(true);
		    fire('#p', pro, 1);
		    console.log("Pro1: "+jc("#p").visible()+", Pro2: "+jc("#p2").visible());
		    //alert(players["player1"][2])
		    detectCollision(jc('#p1'),tank2);
		    player1turn = false;
		    player2turn = true;
            });
			listenForKeyboard();
	    }
	    
	    
	 /**
	 * This function abilita the player2 to shoot.
	 */
	    if (player2turn==true) {
	    	listenForKeyboard();
	    	jc("#tankDx").click(function(point) {
                //window.alert("Yeah it's working");
                jc("#p").visible(false);
                fire('#p2', pro2, -1);
                jc("#p2").visible(true);
                console.log("Pro1: "+jc("#p").visible()+", Pro2: "+jc("#p2").visible());
                //alert(players["player1"][2])
                detectCollision(jc('#p2'),tank1);
                player2turn = false;
                player1turn = true;
            });
	    	 
	    }
            
            
            function listenForKeyboard() {
            	
	            $(document).keypress(function(e) {
	            	
	            	switch (e.keyCode) {
						case 32:
							if (player1turn==true) { //space bar
							    jc("#p2").visible(false);
							    jc("#p").visible(true);
							    fire('#p', pro, 1);
							    console.log("Pro1: "+jc("#p").visible()+", Pro2: "+jc("#p2").visible());
							    //alert(players["player1"][2])
							    detectCollision(jc('#p1'),tank2);
							}
							else if (player2turn==true) { //space bar
				                //window.alert("Yeah it's working");
				                jc("#p").visible(false);
				                fire('#p2', pro2, -1);
				                jc("#p2").visible(true);
				                console.log("Pro1: "+jc("#p").visible()+", Pro2: "+jc("#p2").visible());
				                //alert(players["player1"][2])
				                detectCollision(jc('#p2'),tank1);
				            }
							//break;
						case 97:
							if (player1turn==true) { //right arrow
								var decrease = player1ShootingAngle;
			                    console.log(decrease);
			                    jc('#label_player1').del();
			                    drawPlayer1label(decrease-10);
			                    
			            	} else if (player2turn==true) { //right arrow
								var decrease = player2ShootingAngle;
			                    console.log(decrease);
			                    jc('#label_player2').del();
			                    drawPlayer2label(decrease-10);
			                    
							}
							//break;
							
		            	case 100:
		            		if (player1turn==true) { //left arrow
			            		var increase = player1ShootingAngle;
			                    console.log(increase);
			                    jc('#label_player1').del();
		                    	drawPlayer1label(increase+10);
		                    	
		                    	
		            		} else if (player2turn==true) { //left arrow
		            			var increase = player2ShootingAngle;
			                    console.log(increase);
			                    //console.log(jc('#label_player2').id());
			                    jc('#label_player2').del();
			                    drawPlayer2label(increase+10);
			                    
		            		}
		            		//break;
            	}});}   

              
            
        }
	
	
        /**
         * This function animates a bullet 'p 
         */
        function fire(id,p,lr) { // lr indicates the direction of the shoot
            var G = 9.8; // gravity
            var W = windSpeed; // wind
            var t = 0;
            var v0x = p.v * Math.cos(p.a * Math.PI/180); //initial horizontal velocity
            var v0y = p.v * Math.sin(p.a * Math.PI/180); //initial vertical velocity
            var startX = p.x;
            var startY = p.y;
            var loop = setInterval(function() {
                    if ((p.y < points[p.x][1]) && ((p.x  < 640)&&(p.x  > 0))) {
                            p.y = Math.round(startY - ( v0y * t - (1/2 * G * Math.pow(t,2)) ));
                            p.x = Math.round(startX + (v0x * lr + W) * t);
                            t += .1; // 100 msec (virtual time)
                            jc(id).translateTo(p.x,p.y);
                    }
                    else {clearInterval(loop);
                    //console.log("bullet position: "+jc('#p2').position().x + ", " +jc('#p2').position().y +
                    //            ", tank1 x+radius:" + tank1.x + tank1.r + "," +tank1.y +
                    //            ", tank1 radius:" + tank1.r);
                    //console.log("bullet position: "+jc('#p2').position().x + ", " +jc('#p2').position().y +
                    //            ", tank1 x+radius:" + tank1.x + tank1.r + "," + tank1.y + ", tank1 radius:" + tank1.r)
		    bullets();
		    console.log(detectCollision(jc('#p2'),tank1));
		    console.log(detectCollision(jc('#p'),tank2));
                    } //callback function
            }, 10); //10 msec
        }
        

        /**
         * This function tracks the mouse movements
         * return object with X-position and Y-position
         */
        function trackMouseMovement() {
            console.log();
            var position = jc("canvas").position();
            window.alert(position);
            return position;
        }


        
        // - Music ------------------------------------------------------------
        
        function playMusic() {
            if (
                localStorage["audio"]==undefined ||
                localStorage["audio"]=="true"
                ) {
                introMusic.play();
            }
            if (localStorage["audio"]=="false") {
                introMusic.pause();
            }
        }
        
	
        // This function detects collision
        function detectCollision() {
            if (jc("#p").getCenter().x <= jc("#tankDx").getCenter().x) {
                    //smoke.alert("KABOOM!")
                    // reduce the number of life of player1
                    var l = player2Life-1;
                    return l;
            
            } if (jc("#p2").getCenter().x <= jc("#tankSx").getCenter().x) {
                
                    //smoke.alert("KABOOM!");
                    // reduce the number of life of player2
		    player1Life--;
                    return player1Life;
            }
            
            else {
                
                return false;
            
            }
        }
        
	
	/**
	 * Check if the playerLife == 0.
	 */
	//function chekWins() {
	    
	    
	    
	//}
        
        
        // - END MAIN GAME FUNCTIONS ------------------------------------------
        
        
        /**
         * This function is the initial State of the game.
         */
        function main() {
            // Set this to 'false and make all the elements invisible
            visibility = true;
            // reset the localStorage
            setLocalStorage();
            // Iterate over the array of images and draw the images
            // calling 'onload_images
            for (var i = 0; i < 9; i++) {
                // Calling of 'onload_images with arguments
                    // path - X-postion - Y-position - Id - Visibility(boolean)
                // This if let me not draw the labels.
                if (i==8){
                    continue;
                }
                
                onload_images(
                              arrayOfImages[i][0],
                              arrayOfImages[i][1],
                              arrayOfImages[i][2],
                              arrayOfImages[i][3],
                              visibility
                              );
            };
            
            // Labels events
                // Play label
            //drawTextForMain("PLAY", 40, 100, "label_play")
            // event Handler of the mouse click
            jc('#label_play').click(game);
            jc('#label_play')
            .mouseover(function() {
            	console.log((jc('#label_play').opacity(0.4)));
            })
            .mouseout(function() {
            	console.log((jc('#label_play').opacity(1)));
            })
            ;
            
               // Options label
            //drawTextForMain("OPTIONS", 40, 160, "label_options")
            // event Handler of the mouse click
            jc('#label_options').click(go2OptionsMenu);
            jc('#label_options')
            .mouseover(function() {
            	console.log((jc('#label_options').opacity(0.4)));
            })
            .mouseout(function() {
            	console.log((jc('#label_options').opacity(1)));
            })
            ;
                // How 2 label
            //drawTextForMain("HOW-TO", 40, 220, "label_how2")
             // event Handler of the mouse click
            jc('#label_how2').click(go2How2Menu);
            jc('#label_how2')
            .mouseover(function() {
            	console.log((jc('#label_how2').opacity(0.4)));
            })
            .mouseout(function() {
            	console.log((jc('#label_how2').opacity(1)));
            })
            ;
                // Credit Label
            //drawTextForMain("CREDIT", 40, 280, "label_credit")
            // event Handler of the mouse click
            jc('#label_credit').click(go2CreditMenu);
            jc('#label_credit')
            .mouseover(function() {
            	console.log((jc('#label_credit').opacity(0.4)));
            })
            .mouseout(function() {
            	console.log((jc('#label_credit').opacity(1)));
            })
            ;
            // Audio icon
            
            
            // Call 'onload images with the audio off icon
            // Provides with functionalities to set the
            // music on/off with effects.
                // path - X-postion - Y-position - Id - Visibility(boolean)
            onload_images(
                arrayOfImages[28][0],
                arrayOfImages[28][1],
                arrayOfImages[28][2],
                arrayOfImages[28][3],
                audio
                );
            
            
            // event Handler of the mouse click
            
            
            // to debug
            //window.alert(localStorage[settings["audio"]]);
            //window.alert(localStorage[settings["audio"]]==undefined);
            
            // - Prompts for name
            //askUserForName();
            
        };
        
        
        // - Check Functions --------------------------------------------------
        
        /**
         * This function checks if the mainGame function has already been
         * called. If it is, it resume the game with this function.
         */
        function init() {
            if (!supports_html5_storage()) { return false;}
            gameInProgress = (localStorage["the.game.is.loaded"] == "true");
            if ( gameInProgress == true ) {
                playTheGame();
                
            } else {
                main();
                localStorage["the.chosen.level"] = chosenLevel;
            }
            return true;
        };
        
        
        /**
         * Checks for HTML5 Storage support
         */
        function supports_html5_storage() {
            try {
                return 'localStorage' in window && window['localStorage'] !== null;
        } catch (e) {
            window.alert("Oh no! Your browser does NOT support HTML5 Storage.")
            return false;
            }
        }
        
        
        
        
        // - HTML5 STORAGE FUNCTIONS ------------------------------------------
        
        // stores the gameInProgress variable, so as not to get out the game.
        function changeGameState() {
            if (!supports_html5_storage()) { return false; }
            gameInProgress = true;
            localStorage["the.game.is.loaded"] = gameInProgress;
            return true
        }
        
        
        // - Initialize the storage with default values:
        // the default valeus are stored in an array with the player's name.
        
        function setLocalStorage() {
            for (key in keys1) {
                    localStorage[String(keys1[key])] = players["player1"][key];
            }
            for (key in keys2) {
                    localStorage[String(keys2[key])] = players["player2"][key];
            }
            
            for (key in localStorage) {
                
                console.log(key+", "+localStorage[key]);
            }
        }
        
        
        // - USER SIDE FUNCTIONS ----------------------------------------------
        
        
        
        jc('#arrow')
        .mouseover(function() {
        	console.log((jc('#arrow').opacity(0.2)));
        })
        .mouseout(function() {
        	console.log((jc('#arrow').opacity(1)));
        })
        ;
        
        
        /**
         * Function calls -----------------------------------------------------
         */
        
        init();
        //localStorage.clear();
        //setLocalStorage();
        //listenForKeyboard();
        //$(document).keypress(function(e){
        //        console.log(e.keyCode + ", ")
        //});
        
        
        
    };
